module Holo
  class Command
    class IPC < Command
      class Edit < IPC
        class HoloFile < Edit
          self.summary = 'edit App/holo_files/xx.rb'

          self.description = <<-DESC
          ……
          DESC

          def self.options
            [
              ['--name', 'pod name'],
              ['--version', 'pod version'],
              ['--path', '/path/to/App/holo_files']
            ].concat(super)
          end

          def initialize(argv)
            @name = argv.option('name')
            @version = argv.option('version')
            @path = argv.option('path')
            super
          end

          def validate!
            super
            help! 'A name for the xx.rb is required.' unless @name
            help! 'A version for the xx.rb is required.' unless @version
            help! 'A path for the /path/to/**/xx.rb is required.' unless @path
          end

          # bundle exec holo ipc edit holo-file \
          # --name=XZHNetwork \
          # --version=9.9.9 \
          # --path=/Users/xiongzenghui/Desktop/App/holo_files
          def run
            # 1. 遍历找到 name 对应的 xx.rb
            file_path = Dir.glob(File.expand_path("**/#{@name}.rb", @path)).first
            help! "#{@name} not exist holo file" unless File.exist?(file_path)

            # 2. 读取出 xx.rb
            lines = File.readlines(file_path)

            # 3. 正则式修改 xx.rb 中的标识【版本号】的字段
            # - 1) h.tag = ……
            # - 2) h.version = ……
            tag_regex = Regexp.new(/(\s)*\.tag(\s)*=(\s)*[\"|'](.*)[\"|'](\s)*/)
            version_regex = Regexp.new(/(\s)*\.version(\s)*=(\s)*[\"|'](.*)[\"|'](\s)*/)
            lines.each do |line|
              if line[tag_regex, 4]
                line[tag_regex, 4] = @version
              elsif line[version_regex, 4]
                line[version_regex, 4] = @version
              end
            end

            # 4. 将正则替换后的内容，重新写入到 xx.rb
            File.write(file_path, lines.join(''), mode: "w+")
          end
        end
      end
    end
  end
end